/*

heping
Node.js
复制文件夹里面的 到 另一个文件夹里

*/
const def = {
  rootDir: 'F:\\MyCode\\koaserve',
  targetDir: 'F:\\MyCode\\code-snippets\\test\\target',
  excludeDir: [
    '.git',
    '.gitee',
    'yarn.lock',
    'LICENSE',
    'node_modules'
  ]
}
const fs = require('fs')
const path = require('path')

function backups(def) {
  const { rootDir, targetDir, excludeDir } = def
  if (!fs.existsSync(rootDir) || !fs.existsSync(targetDir)) {
    return
  }
  const mkdir = (dir) => {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true })
    }
  }
  const read = (currentDir, parentDir) => {
    fs.readdirSync(currentDir).forEach(item => {
      if (excludeDir && excludeDir.some(v => v === item)) {
        return
      }
      const dir = path.join(currentDir, item)
      const target = path.join(parentDir ? `${targetDir}\\${parentDir}` : targetDir, item)
      const stat = fs.statSync(dir)
      if (!stat) {
        return
      }
      if (stat.isDirectory()) {
        mkdir(target)
        read(dir, parentDir ? `${parentDir}\\${item}` : item)
      } else if (stat.isFile()) {
        fs.createReadStream(dir).pipe(
          fs.createWriteStream(target)
        )
      }
    })
  }
  read(rootDir)
}

backups(def)
